package in.co.codedoc.util;

import java.io.IOException;
import java.io.InputStream;

public class ConcatenatingInputStream
	extends InputStream
{
	public ConcatenatingInputStream(InputStream... streams)
	{
		if(streams == null || streams.length == 0)
		{
			throw new RuntimeException("Unsupported usage. Pass atleast one stream.");
		}
		
		this.streams = streams;
		this.currentStreamIndex = 0;
	}
	
	@Override
	public int read() throws IOException
	{
		if((currentStreamIndex < streams.length))
		{
			int c = streams[currentStreamIndex].read();
			
			if(c == -1)
			{
				++currentStreamIndex;
				
				if(currentStreamIndex < streams.length)
				{
					return read();
				}
				else
				{
					return -1;
				}
			}
			
			return c;
		}
		else
		{
			return -1;
		}
	}
	
	@Override
	public void close() throws IOException
	{
		super.close();
		
		for(InputStream is:streams)
		{
			try
			{
				is.close();
			}
			catch(Throwable th)
			{
				th.printStackTrace();
			}
		}
	}

	private int currentStreamIndex;
	private InputStream[] streams;
}
